import React, {useEffect, useState} from 'react';
import {Button, Form, Input, InputNumber, Modal, Radio, Select} from 'antd';
import {queryAccount} from "@/services/system";
import {queryMaterialList} from "@/pages/purchase/purchase-apply/service";
import {queryAllProvider} from "@/services/partner";


const PurchaseForm = (props) => {
  const {modalVisible, onCancel, title, onSubmit, requestData} = props;
  const [materialType, setMaterialType] = useState(1)
  const [approvalData, setApprovalData] = useState([])
  const [materialList, setMaterialList] = useState([])
  const [selectedMaterial, setSelectedMaterial] = useState({})
  const [providerData, setProviderData] = useState([])
  const [payDaysVisible, setPayDaysVisible] = useState(false)
  const [form] = Form.useForm();
  const {Option} = Select;
  const {TextArea} = Input;

  const initRecord = {
    requestCode: '',
    materialCode: '',
    materialName: '',
    materialUnit: '',
    num: 1,
    materialPrice: null,
    totalPrice: '',
    materialSupplier: '',
    remark: ''
  }
  const materialTypeChange = (e) => {
    setMaterialType(e.target.value)
    form.setFieldsValue({
      ...initRecord
    })
  }

  useEffect(() => {
    queryAllProvider().then(res => {
      if (res && res.status === '0') {
        setProviderData(res.data)
      }
    })
  }, [])

  const onNumChange = (num) => {
    const materialPrice = form.getFieldValue('materialPrice');
    if (materialPrice) {
      form.setFieldsValue({
        totalPrice: (num * materialPrice).toFixed(2)
      })
    }
  }

  const onPriceChange = (price) => {
    const num = form.getFieldValue('num');
    if (num) {
      form.setFieldsValue({
        totalPrice: (num * price).toFixed(2)
      })
    }
  }

  const onPayTypeChange = e => {
    if (e.target.value === 1) {
      setPayDaysVisible(false)
    }else {
      setPayDaysVisible(true)
    }
  }

  useEffect(() => {
    queryAccount({
      pageSize: 99999,
      pageNum: 1
    }).then(res => {
      setApprovalData(res.result.records)
    })
  }, [])

  const onApprovalSearch = (v) => {
    if (v) {
      queryAccount({
        staffName: v,
        pageSize: 99999,
        pageNum: 1
      }).then(res => {
        setApprovalData(res.result.records)
      })
    }
  }

  const onSearchMaterialByCode = async (e) => {
    if ((e.target && e.target.value) || (!e.target && e)) {
      const param = {materialCode: e.target ? e.target.value : e, pageNum: 1, pageSize: 999999};
      const res = await queryMaterialList(param)
      setMaterialList(res.result.records)
    } else {
      form.setFieldsValue({
        materialCode: '',
        materialName: '',
        materialUnit: '',
        materialPrice: '',
        materialSupplier: '',
      })
    }
  }

  const handleMaterial = (record) => {
    const material = JSON.parse(record)
    const num = form.getFieldValue('num');
    if (num) {
      form.setFieldsValue({
        totalPrice: num * material.materialPrice
      })
    }
    setSelectedMaterial(material)
    form.setFieldsValue({
      ...material,
    })
  }

  const handelSubmit = (status) => {
    form.validateFields([
      'materialCode',
      'materialName',
      'materialUnit',
      'materialPrice',
      'materialSupplier',
      'num',
      'requestRemark',
      'approvalBy',
      'materialType',
      'payType',
      'payDays',
    ]).then(val => {
      //console.log((val)
      if (!val.materialType) {
        val.materialType = requestData.materialType
      }
      onSubmit({...val, requestStatus: status})
    });
  }

  return (
    <Modal
      destroyOnClose
      title={title}
      width={800}
      visible={true}
      onCancel={() => onCancel()}
      footer={
        [
          <Button key="save" type="primary" onClick={() => handelSubmit(1)}>
            保存并提交
          </Button>,
          <Button key="draft" onClick={() => handelSubmit(0)}>
            存为草稿
          </Button>,
          <Button
            key="cancel" onClick={() => onCancel()}
          >
            取消
          </Button>
        ]}
      wrapClassName={'purchaseModal'}
    >
      <Form
        layout={'horizontal'}
        form={form}
        initialValues={{
          ...requestData
        }}
      >
        <Form.Item label="物料类型" name="materialType">
          <Radio.Group onChange={(e) => materialTypeChange(e)}>
            <Radio value={1}>新物料</Radio>
            <Radio value={2}>选择已有物料</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item label="物料编码" name="materialCode" rules={[
          {
            required: true,
            message: '物料编码是必填项'
          }
        ]}>
          {
            materialType === 1 ? (
              <Input
                placeholder='请输入物料编码 格式为A0' allowClear/>
            ) : (
              <Select showSearch
                      onSearch={(v) => onSearchMaterialByCode(v)}
                      onChange={(v) => handleMaterial(v)}
              >
                {materialList.map(item => {
                  return <Option
                    key={JSON.stringify(item)}>{item.materialName}({item.materialCode})</Option>
                })}
              </Select>
            )
          }
        </Form.Item>
        <Form.Item label="物料名称" name="materialName"
                   rules={[
                     {
                       max: 32,
                       message: '物料名称最大长度为32'
                     },
                     {
                       whitespace: true,
                       message: '请不要输入空格'
                     },
                     {
                       required: true,
                       message: '物料名称是必填项'
                     }
                   ]}>
          <Input disabled={materialType === 2} maxLength={33} placeholder={'请输入物料名称'}/>
        </Form.Item>
        <Form.Item label="计量单位" name="materialUnit" rules={[
          {
            required: true,
            message: '计量单位是必填项'
          }
        ]}>
          <Input disabled={materialType === 2} maxLength={32} placeholder={'请输入计量单位'}/>
        </Form.Item>
        <Form.Item label="物料单价（元）" name={'materialPrice'}
                   rules={[
                     {
                       required: true,
                       message: '物料单价是必填项'
                     },
                     {
                       pattern: /^\d+(\.\d{0,2})?$/,
                       message: '只能输入两位小数'
                     }
                   ]}
        >
          <InputNumber disabled={materialType === 2}
                       style={{width: '100%'}}
                       placeholder={'请输入单价'}
                       min={0.01}
                       max={99999999.99}
                       step={0.01}
                       stringMode
                       onChange={(v) => onPriceChange(v)}/>
        </Form.Item>
        <Form.Item label="数量" name={'num'} rules={[
          {
            required: true,
            message: '数量是必填项'
          }
        ]}>
          <InputNumber placeholder={'数量'} min={1} style={{width: '100%'}} onChange={(v) => onNumChange(v)}/>
        </Form.Item>
        <Form.Item label="总价（元）" name={'totalPrice'}>
          <Input disabled={true}/>
        </Form.Item>
        <Form.Item label="供应商" name="materialSupplier">
          <Select disabled={materialType === 2}>
            {
              providerData.map(i => {
                return <Option value={i.providerId} key={i.providerId}>{i.providerName}</Option>
              })
            }
          </Select>
        </Form.Item>
        <Form.Item label="付款方式" name="payType">
          <Radio.Group onChange={(e) => onPayTypeChange(e)}>
            <Radio value={1}>现金</Radio>
            <Radio value={2}>月结</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item label="月结天数" name={'payDays'} style={{display: payDaysVisible? '': 'none'}}
                   rules={[
                     {
                       pattern: /^[1-9]\d*$/,
                       message: '只能输入整数'
                     }
                   ]}
        >
          <InputNumber placeholder={'月结天数'} min={1} style={{width: '100%'}}/>
        </Form.Item>
        <Form.Item label="备注" name="requestRemark">
          <TextArea/>
        </Form.Item>
        <Form.Item label="审批人" name="approvalBy" rules={[
          {
            required: true,
            message: '审批人是必填项'
          }
        ]}>
          <Select
            showSearch
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={false}
            onSearch={(v) => onApprovalSearch(v)}
            notFoundContent={null}
          >
            {approvalData.map(item => {
              return <Option value={item.userId} key={item.userId}>{item.staffInfo.realName}</Option>
            })}
          </Select>
        </Form.Item>
      </Form>
    </Modal>
  );
};
export default PurchaseForm;
